from urllib.parse import urlparse

from django.db import models
from django.utils.timezone import now
from django.conf import settings
from django_ckeditor_5.fields import CKEditor5Field
import os
from dotenv import load_dotenv, set_key

#基类模型，将共有的时间字段抽象出来
class BaseModel(models.Model):
    id = models.AutoField(primary_key=True)#主键id，自增长
    created_date = models.DateTimeField('创建时间', default=now)
    modified_date = models.DateTimeField('最后修改时间', default=now)
    rank = models.IntegerField('排序', default=0, blank=True, null=True)#排序字段,数字越大越靠前
    class Meta:
        abstract = True

#站点信息模型
class SiteInfo(BaseModel):
    OAUTH_CHOICES = [
        ('qq', 'QQ登录'),
        ('weibo', '微博登录'),
        ('github', 'GitHub登录'),
        ('gitee', 'Gitee登录')
    ]
    name = models.CharField('网站名称', max_length=50)
    title = models.CharField('网站标题', max_length=100,blank=True,null=True)
    keywords = models.CharField('关键字', max_length=200,blank=True, null=True)
    description = CKEditor5Field(verbose_name='网站描述',config_name='extends',blank=True, null=True)
    #博主信息,这里使用了默认的用户模型，默认选择身份为博主的用户
    bloguser = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='博主', on_delete=models.CASCADE,default=1)
    domain = models.CharField('网站域名', max_length=100, default='localhost')
    icp = models.CharField('ICP备案号', max_length=20, blank=True, null=True)
    #公安备案号
    public_record = models.CharField('公安备案号', max_length=20, blank=True, null=True)

    copyright = models.CharField('版权信息', max_length=100, blank=True, null=True)
    logo = models.ImageField('网站Logo', upload_to='blog/logo', blank=True, null=True)
    icon = models.ImageField('网站Icon', upload_to='blog/icon', blank=True, null=True)
    background = models.ImageField('网站背景图', upload_to='blog/background', blank=True, null=True)
    #是否开启打赏
    is_reward = models.BooleanField('是否开启打赏', default=False)
    #微信打赏二维码
    wechat_reward_qrcode = models.ImageField('微信收款码', upload_to='blog/reward_qrcode', blank=True, null=True)
    #支付宝打赏二维码
    alipay_reward_qrcode = models.ImageField('支付宝收款码', upload_to='blog/reward_qrcode', blank=True, null=True)
    #是否使用第三方登录
    is_oauth = models.BooleanField('是否使用第三方登录', default=False)
    oauth_list = models.ManyToManyField('OauthConfig', verbose_name='第三方登录',blank=True)
    class Meta:
        verbose_name = '站点信息'
        verbose_name_plural = '站点信息'
        ordering = ['rank']


#友情链接模型
class FriendLink(BaseModel):
    name = models.CharField('链接名称', max_length=50)
    url = models.URLField('链接地址')
    logo = models.ImageField('Logo默认图片', upload_to='friend_link', default='default/friend_link/default_link.jpg', blank=True, null=True)
    logo_url = models.URLField('Logo地址', blank=True, null=True)
    description = models.TextField('链接描述', max_length=100, blank=True, null=True)
    #是否失联
    is_lost = models.BooleanField('是否失联', default=False)
    class Meta:
        verbose_name = '友情链接'
        verbose_name_plural = '友情链接'
        ordering = ['rank']
    def save(self, *args, **kwargs):
        if not self.logo:
            self.logo = 'default/friend_link/default_link.jpg'
        super().save(*args, **kwargs)

#轮播图模型
class Carousel(BaseModel):
    name = models.CharField('轮播图名称', max_length=50)
    image = models.ImageField('本地上传图片', upload_to='blog/carousel', blank=True, null=True, help_text='本地上传图片优先于网络图片,建议尺寸大于580px*420px')
    url = models.URLField('图片网络地址', blank=True, null=True)
    #是否启用网络图片
    is_enable_url = models.BooleanField('是否启用网络图片', default=False)
    is_show = models.BooleanField('是否显示', default=True)
    class Meta:
        verbose_name = '轮播图'
        verbose_name_plural = '轮播图'
        ordering = ['rank']
#公告模型
class Announcement(BaseModel):
    title = models.CharField('公告标题', max_length=50)
    content = models.TextField('公告内容')
    #是否跳转到其他页面
    is_jump = models.BooleanField('是否跳转', default=False)
    jump_url = models.CharField('跳转地址', max_length=100, blank=True, null=True)
    #系统公告
    is_system = models.BooleanField('是否系统公告', default=False)

    class Meta:
        verbose_name = '公告'
        verbose_name_plural = '公告'

#菜单模型
class Menu(BaseModel):
    name = models.CharField('菜单名称', max_length=25)
    url = models.CharField('菜单地址', max_length=40)
    icon = models.CharField('菜单图标', max_length=40, blank=True, null=True)
    parent = models.ForeignKey('self', verbose_name='父菜单', blank=True, null=True, on_delete=models.SET_NULL)
    is_show = models.BooleanField('是否显示', default=True)

    @property
    def children(self):
        return Menu.objects.filter(parent=self)
    #父菜单显示：父菜单-子菜单
    def get_menu_name(self):
        if self.parent:
            return self.parent.get_menu_name()+'-'+self.name
        else:
            return self.name
    @property
    def parent_name(self):
       return self.parent.name if self.parent else ''

    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '菜单'
        verbose_name_plural = '菜单'
        ordering = ['rank']
#页面模型
#组件模型



# 加载 .env 文件
load_dotenv('.env')

# 第三方登录模型
class OauthConfig(BaseModel):
    OAUTH_TYPE_CHOICES = [
        ('qq', 'QQ登录'),
        ('weibo', '微博登录'),
        ('github', 'GitHub登录'),
        ('gitee', 'Gitee登录')
    ]
    name = models.CharField('第三方类型', max_length=20, choices=OAUTH_TYPE_CHOICES)
    app_id = models.CharField('APP ID', max_length=100, blank=True, null=True)
    app_key = models.CharField('APP Secret', max_length=100, blank=True, null=True)
    redirect_uri = models.CharField('回调地址', max_length=100, blank=True, null=True)
    is_enable = models.BooleanField('是否启用', default=False)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.update_env_file()

    def update_env_file(self):#更新环境变量文件
        if self.name == 'qq':
            set_key('.env', 'QQ_CLIENT_ID', self.app_id)
            set_key('.env', 'QQ_CLIENT_SECRET', self.app_key)
        elif self.name == 'weibo':
            set_key('.env', 'WEIBO_CLIENT_ID', self.app_id)
            set_key('.env', 'WEIBO_CLIENT_SECRET', self.app_key)
        elif self.name == 'github':
            set_key('.env', 'GITHUB_CLIENT_ID', self.app_id)
            set_key('.env', 'GITHUB_CLIENT_SECRET', self.app_key)
        elif self.name == 'gitee':
            set_key('.env', 'GITEE_CLIENT_ID', self.app_id)
            set_key('.env', 'GITEE_CLIENT_SECRET', self.app_key)
        else:
            raise ValueError(f"未知的第三方登录类型: {self.name}")

    class Meta:
        verbose_name = '第三方登录'
        verbose_name_plural = '第三方登录'
        ordering = ['rank']

    def __str__(self):
        return self.name

